from PyQt5.Qt import *
import sys


class ui(QWidget):
    signal=pyqtSignal()
    def __init__(self):
        super().__init__()
        self.layout=QVBoxLayout(self)
        # text_Elit=QTextEdit()
        self.btn=QPushButton()
        # self.layout.addWidget(text_Elit)
        # self.layout.addWidget(btn)
        #
        self.tablewiget=QTableWidget(4,3)
        # tablewiget.setRowCount(4)
        # tablewiget.setColumnCount(3)
        self.tablewiget.horizontalHeader()
        #.setSectionResizeMode(QHeaderView.stretch)
        #填充数据
        self.tablewiget.setHorizontalHeaderLabels(["姓名",'性别','体重(kg)'])
        self.tablewiget.setVerticalHeaderLabels(['行1','行2','行3','行4'])

        self.tablewiget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) #自动伸缩模式
        self.tablewiget.resizeColumnsToContents()#表格与文字高度匹配
        self.tablewiget.resizeRowsToContents() #表格与文字宽度匹配
        self.tablewiget.setAlternatingRowColors(True)  # 行是否自动变色
        self.tablewiget.setSortingEnabled(True)  #点击排序

        self.tablewiget.setItem(0,0,QTableWidgetItem('zhangsan'))
        self.tablewiget.setItem(0,1,QTableWidgetItem('zhangsan1'))
        self.tablewiget.setItem(0,2,QTableWidgetItem('zhangsan2'))

        self.layout.addWidget(self.tablewiget)
        self.btn.clicked.connect(self.add_pushbtn)



        #支持右键
        self.tablewiget.setContextMenuPolicy(Qt.CustomContextMenu)
        #将右键菜单绑定到槽函数
        self.tablewiget.customContextMenuRequested.connect(self.generateMenu)

    def generateMenu(self,pos):
        row_num = -1
        for i in self.tablewiget.selectionModel().selection().indexes():
            row_num = i.row()
            print('点击了右键选中了%s行'%row_num)



    def add_pushbtn(self):
        self.layout.addWidget(QPushButton('新增按钮'))



if __name__ == '__main__':

    app=QApplication(sys.argv)
    window=ui()
    window.show()
    sys.exit(app.exec_())

